const path = require('path');
const express = require('express');
const { finished } = require('stream');
const app = express();
const storage = express();
const moment = require('moment'); // require

const http = require('http').Server(app);
const io = require('socket.io')(http,{pingTimeout:60000,pingInterval:60000});
const getDao = require('./libs/databaseService');
const Client = require('./libs/client');
const { version } = require('moment');


const port = process.env.PORT || 3000
const dataroot =  path.resolve(process.env.DATA_ROOT||__dirname);
const dbroot = path.join(dataroot ,'database');
const storageroot = path.join(dataroot , 'storage');
const timeZone = "Asia/Shanghai";
console.log(dbroot,storageroot);
process.env.DB_ROOT = dbroot;
process.env.STORAGE_ROOT = storageroot;

console.log('port:',port);
let clientStack = {};
function initClientSocket(socket){
    if(socket){
        let socketId = socket.id;
        if(Object.hasOwnProperty.call(clientStack, socketId)){

        }else{
            let client= new Client(socket);
            clientStack[socketId] = client;
        }
    
        //注册客户端断开链接的处理逻辑
        socket.on('disconnect', function (reason) {
            if(Object.hasOwnProperty.call(clientStack, socketId)){
                delete clientStack[socketId];
            }
            console.log("client disconnected by",reason);
         });
    }else{
        return;
    }
}
async function main(){
    const dao = getDao();
    //初始化页面视图
    app.set('views', './views');
    app.set('view engine', 'pug');
    app.use(express.static('views'));
    storage.use(express.static('storage'));
    app.use('/storage',storage);
    //首页链接
    app.get('/', function (req, res) {
        dao.listProjects().then( projects =>{

            let newProjects = projects.map( project => {
                console.log(project.currentVersion);
                return {
                    projectId:project.projectId,
                    projectName:project.projectName,
                    description:project.description,
                    currentVersionId:project.currentVersionId,
                    projectType:project.projectType,
                    updatedAt: moment(project.updatedAt).tz(timeZone).format("YYYY-MM-DD HH:mm:ss"),
                    currentVersion: project.currentVersion === null ? null : {filePath:project.currentVersion.filePath,
                                    webPath:project.currentVersion.webPath,
                                    changeList:project.currentVersion.changeList,
                                    uploadDateTime: moment(project.currentVersion.uploadDateTime).tz(timeZone).format("YYYY-MM-DD HH:mm:ss")}
                }
            });
            console.log(newProjects);
            res.render('index', { title: '税务系统原型', projects:newProjects })
        }).catch(e=>{
            console.error(e);
        });
        
    });

    //Show Project Detail
    app.get('/project/:id', function (req, res) {
        let projectId =  req.params.id;
        dao.findProjectById(projectId).then( project =>{
            console.log(project);
            let versionData = project.versions?project.versions.map((version)=>{
                let tmp = {
                    webPath:version.webPath,
                    changeList:version.changeList,
                    uploadDateTime: moment(version.uploadDateTime).tz(timeZone).format("YYYY-MM-DD HH:mm:ss")
                }
                return tmp;
            }):[];
            let data ={
                projectId:project.projectId,
                projectName:project.projectName,
                description:project.description,
                currentVersionId:project.currentVersionId,
                projectType:project.projectType,
                updatedAt: moment(project.updatedAt).tz(timeZone).format("YYYY-MM-DD HH:mm:ss"),
                versions:versionData
            }
            res.render('project', { title: '税务系统原型', project:data })
        }).catch(e=>{
            console.error(e);
        });
        
    });
    //Add New Project
    app.get('/addNewProject', function (req, res) {
        dao.addProject({'projectName':'测试项目','description':'测试项目'}).then(modle =>{
                console.log(modle);
            }).catch(e=>{
                console.error(e);
            });
    });
    //Add new version
    app.get('/addNewVersion', function (req, res) {

        dao.addVersion({'projectId':2,'filePath':path.join(process.env.STORAGE_ROOT ,'测试项目'),changeList:'change list.',uploadDateTime:new Date()}).then(modle =>{
                console.log(modle);
            }).catch(e=>{
                console.error(e);
            });
    });
    
    //配置客户端事件。
    io.on('connection', function(socket) {
        initClientSocket(socket);
        console.log('A user connected');
     });
    
     dao.connect().then((initDataBase)=>{
        if(initDataBase){
            http.listen(port, () => {
                console.log(`Example app listening at http://localhost:${port}`)
            });
        }else{
            console.log('Init database falid.');
        }
    });
}

main();